#!/bin/bash
# PHP后台部署脚本

echo "=========================================="
echo "定位后台服务器 - PHP版本部署"
echo "=========================================="
echo ""

# 检查PHP
if ! command -v php &> /dev/null; then
    echo "❌ 错误: 未找到PHP，请先安装PHP 7.4+"
    echo ""
    echo "Ubuntu/Debian: sudo apt install php php-cli php-mbstring php-xml php-curl"
    echo "CentOS/RHEL: sudo yum install php php-cli php-mbstring php-xml"
    exit 1
fi

PHP_VERSION=$(php -v | head -n 1)
echo "✅ PHP版本: $PHP_VERSION"
echo ""

# 检查Composer
if ! command -v composer &> /dev/null; then
    echo "⚠️  未找到Composer，正在安装..."
    echo ""
    
    # 下载Composer安装脚本
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php composer-setup.php --quiet
    rm composer-setup.php
    
    # 移动到系统路径
    if [ -f "composer.phar" ]; then
        chmod +x composer.phar
        sudo mv composer.phar /usr/local/bin/composer 2>/dev/null || mv composer.phar composer
        echo "✅ Composer安装完成"
    else
        echo "❌ Composer安装失败"
        exit 1
    fi
fi

echo "✅ Composer版本: $(composer --version 2>/dev/null || ./composer --version)"
echo ""

# 安装PHP依赖
echo "📥 安装PHP依赖包..."
if command -v composer &> /dev/null; then
    composer install
elif [ -f "composer" ]; then
    php composer install
else
    echo "❌ 无法运行Composer"
    exit 1
fi

if [ $? -ne 0 ]; then
    echo "❌ 依赖安装失败"
    exit 1
fi

# 创建数据目录
mkdir -p data
chmod 755 data

# 创建日志目录
mkdir -p logs
chmod 755 logs

echo ""
echo "✅ 部署完成！"
echo ""
echo "=========================================="
echo "启动方式："
echo "=========================================="
echo ""
echo "1. 启动WebSocket服务器（推荐，实时通信）："
echo "   php server.php"
echo ""
echo "2. 使用PHP内置服务器（HTTP API）："
echo "   php -S 0.0.0.0:8080 api.php"
echo ""
echo "3. 使用Apache/Nginx："
echo "   将api.php设置为入口文件"
echo ""
echo "=========================================="


